package com.fengba.nanzhi.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.ToastUtil;
import android.os.CountDownTimer;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by duan on 2018/4/2.
 */

public class Reg extends AppCompatActivity {


    //手机号
    private EditText Rphone;
    //密码
    private EditText Rpassword;
    //眼睛图片 ImageButton
    private ImageButton Reye;
    //验证码
    private Button YZMButton;

    private TimeCount time;

    //邀请码
    private EditText Rinvite;
    //XX
    private ImageButton Rclose;
    //确认
    private Button Rindex;

    //验证码
    private EditText Rcode;

    //短信编码
    private  String msg_id = "0";

    //返回
    private ImageButton Rretun;

    //同意按钮
    private ImageButton Rgg;

    //用户协议
    private TextView YHXY;

    private boolean flag=true;

    //菊花
    private ProgressBar Rjuhua;

    public Reg() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fx_reg);
        Rphone = (EditText) findViewById(R.id.Rphone);
        Rcode = (EditText) findViewById(R.id.Rcode);
        Rphone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        Rpassword = (EditText) findViewById(R.id.Rpassword);
        Rinvite = (EditText) findViewById(R.id.Rinvite);
        Rphone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        time = new TimeCount(60000, 1000);
        Rjuhua = (ProgressBar) findViewById(R.id.Rjuhua);




        /**
         * 更换眼睛
         */
        Reye = (ImageButton ) findViewById(R.id.Reye);
        Reye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int type=  Rpassword.getInputType();
                if (type == 109)
                {
                    Rpassword.setInputType(129);
                    ((ImageButton)view).setImageDrawable(getResources().getDrawable(R.mipmap.img_0003));
                }else
                {
                    Rpassword.setInputType(109);
                    ((ImageButton)view).setImageDrawable(getResources().getDrawable(R.mipmap.img_0002));
                }
            }
        });
        /**
         * 叉叉
         */
        Rclose =(ImageButton)findViewById(R.id.Rclose);
        Rclose.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view)
            {
                Rpassword.setText("");
                Rclose.setVisibility(View.INVISIBLE);
            }

        });
        /**
         * 显示xx
         */
        Rpassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ////Log.i(TAG, "输入文字中的状态，count是输入字符数");

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

                ////Log.i(TAG, "输入文本之前的状态");
            }

            @Override
            public void afterTextChanged(Editable s) {
                ////Log.i(TAG, "输入文字后的状态");
                Rclose.setVisibility(View.VISIBLE);
            }
        });
        /**
         * 注册POST
         */
        Rindex =(Button)findViewById(R.id.Rindex);
        Rindex.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view)
            {
                Rjuhua.setVisibility(ProgressBar.VISIBLE);
                if (flag) {
                    OKManager.getInstance().type2016(
                            String.valueOf(Rphone.getText()),
                            String.valueOf(Rpassword.getText())
                            ,String.valueOf(Rinvite.getText()),
                            msg_id,
                            String.valueOf(Rcode.getText())
                            ,new OKManager.func4() {
                                @Override
                                public void onResponse(JSONObject jsonObject) {
                                    try {
                                        if (jsonObject.get("code").equals(0)) {
                                            Intent intent = new Intent(Reg.this, Login.class);
                                            startActivity(intent);
                                        } else {
                                            ToastUtil.showToast(Reg.this,jsonObject.get("message").toString(),Rjuhua);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onFailure(String string) {
                                    Toast.makeText(Reg.this, "网络错误", Toast.LENGTH_SHORT).show();
                                    Rjuhua.setVisibility(ProgressBar.INVISIBLE);
                                }
                            });




                }else
                {
                    Rjuhua.setVisibility(ProgressBar.INVISIBLE);
                    Toast.makeText(Reg.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                }
            }

        });

        YZMButton = (Button) findViewById(R.id.YZMButton);
        Rcode.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        YZMButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                if (Rphone.length() == 11) {
                    time.start();
                    OKManager.getInstance().type2015(
                            "1",
                            String.valueOf(Rphone.getText())
                            ,new OKManager.func4() {
                                @Override
                                public void onResponse(JSONObject jsonObject) {
                                    try {
                                        if (jsonObject.get("code").equals(0)) {
                                            JSONObject data = (JSONObject) jsonObject.get("data");
                                            msg_id = data.get("message").toString();

                                        } else {
                                            Toast.makeText(Reg.this, jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                                            Rjuhua.setVisibility(ProgressBar.INVISIBLE);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onFailure(String string) {
                                    Toast.makeText(Reg.this, "网络错误", Toast.LENGTH_SHORT).show();
                                    Rjuhua.setVisibility(ProgressBar.INVISIBLE);
                                }
                            });



                } else {
                    Toast.makeText(Reg.this, "请输入正确手机号", Toast.LENGTH_SHORT).show();
                }
            }


        });
        /**
         * 返回
         */
        Rretun = (ImageButton) findViewById(R.id.Rretun);
        Rretun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Reg.this, Login.class);
                startActivity(intent);
            }
        });
        /**
         * 是否同意用户协议
         */
        Rgg = (ImageButton) findViewById(R.id.Rgg);
        Rgg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag)
                {
                    ((ImageButton)view).setImageDrawable(getResources().getDrawable(R.mipmap.nogg));
                    flag=false;
                }else
                {
                    ((ImageButton)view).setImageDrawable(getResources().getDrawable(R.mipmap.img_0005));
                    flag=true;
                }

            }
        });

        YHXY = findViewById(R.id.YHXY);
        YHXY.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Reg.this, Yhxy.class);
                startActivity(intent);
            }
        });

    }//都在这里打



    //计时器实现
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            YZMButton.setClickable(false);
            YZMButton.setText("("+millisUntilFinished / 1000 +") ");
        }

        @Override
        public void onFinish() {
            YZMButton.setText("重新获取验证码");
            YZMButton.setClickable(true);
        }
    }

    /**
     * 隐藏软键盘
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
